﻿using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace ServiceCore.WebApi.jwt
{
    public class DateTimeJsonConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(
            ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options)
        {
            string dateString = reader.GetString();
            //if (dateString.Contains("T"))
            //    dateString = dateString.Replace("T", " ");
            //if (dateString.Split(' ').Length == 1)
            //    dateString = dateString + " 00:00:00";
            if (!DateTime.TryParse(dateString, out DateTime date))
            {
                return DateTime.MinValue;
            }
            //return DateTime.ParseExact(date.ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
            return date;
        }
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
        }
    }
}
